<template>
  <div id="globalHeader">
    <!-- Menu -->
    <div class="menu-demo">
      <a-menu mode="horizontal" :selected-keys="selectedKey">
        <a-menu-item class="logo-container" key="0" :style="{ padding: 0, marginRight: '38px' }" disabled>
          <div class="title-bar">
            <img src="../assets/logo.png" alt="logo" width="32" class="logo">
            <div class="title">OJ</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in avilibleRoute" :key="`/${item.path}`" @click="handleTo(item.path)">{{ item.name
          }}</a-menu-item>
      </a-menu>
    </div>
    <!-- userInfo -->
    <div style="width: 120px;">
      <template v-if="loginUser.userRole === NOT_LOGIN">
        <a-button size="small">登录</a-button>
      </template>
      <template v-else>
        <div>
          {{ loginUser.userName }}
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { NOT_LOGIN } from '@/access/accessEnum.ts';
import { checkAuth } from '@/access/accessRole.ts';
import routes from '@/router/routes.ts';
import { useUserStore } from '@/stores/user.ts';
import { computed, ref, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';

//路由信息
const userStore = useUserStore()
const route = useRoute()
const router = useRouter()
//动态获取路由配置中的basiclayout的路由信息
const routeList = routes.filter(route => route.path === '/')[0]?.children
//过滤掉不展示和无权限的菜单  1.根据hidden  2.根据权限
const avilibleRoute = routeList.filter(route => {
  //如果不用显示
  if (!route.meta.isHidden) return false

  if (!checkAuth(userStore.loginUser, route.meta.access)) return false

  return true
})

//默认选择路由key
const selectedKey = ref<string[]>([route.path])

//路由跳转
const handleTo = (key: string) => {
  router.push(`/${key}`)
}

//路由菜单高亮
watch(() => route.path, (newVal) => {
  selectedKey.value = [newVal]
}, { immediate: true }) //确保首次加载也会成功


//获取用户登录态
const loginUser = computed(() => {
  console.log(userStore.loginUser.userRole);

  return userStore.loginUser
})

//模拟三秒后把用户信息设置为登录

</script>

<style scoped>
#globalHeader {
  display: flex;
  align-items: center;
}

.menu-demo {
  box-sizing: border-box;
  width: 100%;
  background-color: var(--color-neutral-2);
}

.title-bar {
  height: 32px;
  width: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.title-bar .logo {
  border-radius: 10px;
  opacity: 0.8;
}

.title-bar .title {
  margin-left: 1rem;
  color: black;
  font-weight: bold;
  letter-spacing: 1px;
}
</style>
